package com.example.xzs.admin.userlogin.controller;

import com.example.xzs.admin.userlogin.JsoResult.JsonResult;
import com.example.xzs.admin.userlogin.pojo.authentication.CurrentPrincipal;
import com.example.xzs.admin.userlogin.pojo.param.UserLogin;
import com.example.xzs.admin.userlogin.pojo.param.UserRegistration;
import com.example.xzs.admin.userlogin.service.IUserService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Slf4j
@RestController
@Api(tags = "1. 登录与注册")
@RequestMapping("/api/")
public class UserController {
    @Autowired
    IUserService iUserService;
    //用户注册
    @PostMapping("/student/user/register")
    @ApiOperation("注册")
    @ApiOperationSupport(order = 1)
        public JsonResult register(@Valid UserRegistration userRegistration){
          log.debug("开始执行注册功能");
          iUserService.insertUserData(userRegistration);
          return JsonResult.ok();

    }
    @PostMapping("/user/login")
//    @PreAuthorize("hasAuthority('ADMIN')")
    @ApiOperation("登录")
    @ApiOperationSupport(order = 2)
    public  JsonResult login(@Valid UserLogin userLogin,@ApiIgnore HttpServletRequest request){
        log.debug("开始登录");
        String remoteAddr=request.getRemoteAddr();//获取IP
        String userAgent=request.getHeader("User-Agent");//获取信息
        String jwt=iUserService.login(userLogin,remoteAddr,userAgent);
       return JsonResult.ok(jwt);
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    @ApiOperationSupport(order = 90)
    public JsonResult logout(@AuthenticationPrincipal @ApiIgnore HttpServletRequest request, HttpServletResponse response) {
        log.debug("开始处理【退出登录】的请求，无参数");
        iUserService.logout(request,response);
        return JsonResult.ok();
    }

}
